from django.contrib.auth import login, authenticate
from django.shortcuts import render, HttpResponse, redirect, reverse
from django.views.generic import FormView
from user.forms import LoginForm, RegisterForm
from user.models import User


# 登录
class Login(FormView):
    form_class = LoginForm
    template_name = 'user/login.html'

    def post(self, request, *args, **kwargs):
        form = self.form_class(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            user = authenticate(request, username=data["username"], password=data["password"])
            if user:
                login(request, user)
                return redirect(reverse('goods:index'))
        message = "账号或密码错误"
        return render(request, 'user/login.html', context={'message': message, "form":form})


# 注册
class Register(FormView):
    form_class = RegisterForm
    template_name = 'user/register.html'

    def post(self, request, *args, **kwargs):
        form = self.form_class(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            User.objects.create(username=data["username"], password=data["password"],email=data["email"])
            return redirect(reverse('users:login'))
        return render(request, "user/register.html", context={"form": form})
